package com.zhentao.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.exception.CustomException;
import com.zhentao.mapper.TbMenuMapper;
import com.zhentao.mapper.TbRoleMapper;
import com.zhentao.mapper.TbRoleMenuMapper;
import com.zhentao.mapper.TbUserRoleMapper;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.common.enums.RedisConstants;
import com.zhentao.model.common.pojo.management.*;
import com.zhentao.service.ITbMenuService;
import com.zhentao.userLocal.AdminUserThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mp
 * @since 2025-01-03
 */
@Service
public class TbMenuServiceImpl extends ServiceImpl<TbMenuMapper, TbMenu> implements ITbMenuService {

    @Resource
    private TbMenuMapper tbMenuMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * @param
     * @return com.zhentao.model.common.dtos.ResponseResult
     * @description 动态查询菜单
     * @author mhy
     * @date 2024/12/26 21:08
     */
    @Override
    public ResponseResult menuList() {
        UserInfo user = AdminUserThreadLocalUtils.getUserInfo();
        if (StringUtils.checkValNull(user)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.CHARGE_USER_DATA_NOT_EXIST);
        }
        String key =RedisConstants.SYS_PERMISSION_SELECT_CACHE_KEY+user.getId();
        // 每次查询首先从缓存中查询，查询缓存中是否存在
        List<TbMenu> permissions;
        try {
            String permissionJSON = redisTemplate.opsForValue().get(key);
            if(!com.alibaba.cloud.commons.lang.StringUtils.isBlank(permissionJSON)){
                List<TbMenu> permissionCache = JSON.parseArray(permissionJSON, TbMenu.class);

//                return ResponseResult.okResult(permissionCache);
            }
            // 查询菜单
            permissions = tbMenuMapper.selectMenuByUserIds(user.getId());
            if(permissions != null && permissions.size() > 0){
                for (TbMenu permission : permissions) {
                    List<TbMenu> permissionsList = tbMenuMapper.getAllByPerId(permission.getId());
                    permission.setChildren(permissionsList);
                }
            }
//            assert permissions != null;
//            permissions.removeIf(permission -> Long.parseLong(permission.getId().toString()) != 0L);
        } catch (Exception e) {
            throw new CustomException(AppHttpCodeEnum.NULL_EXCEPTION);
        }
        // 存放在缓存当中
        redisTemplate.opsForValue().set(key, JSON.toJSONString(permissions));
        // 设置过期时间
        redisTemplate.expire(key, 30, TimeUnit.MINUTES);
        return ResponseResult.okResult(permissions);
    }
    @Resource
    private TbUserRoleMapper sysUserRoleMapper;
    @Resource
    private TbRoleMapper roleMapper;
    private TbRole getRole() {
        UserInfo sysUser = AdminUserThreadLocalUtils.getUserInfo();
        TbUserRole userRole = sysUserRoleMapper.selectOne(Wrappers.<TbUserRole>lambdaQuery()
                .eq(TbUserRole::getUserId, sysUser.getId()));
        TbRole tbRole = roleMapper.selectOne(Wrappers.<TbRole>lambdaQuery().eq(TbRole::getId, userRole.getRoleId()));

        return tbRole;
    }
    @Override
    public ResponseResult addMenu(TbMenu tbMenu) {
        // 判断权限
        TbRole role = getRole();
        if (!role.getRoleName().equals("超级管理员")) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //判断参数
        if (tbMenu == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 如果没有父级菜单则设置为0
        Integer parentId = tbMenu.getParentId();
        if (parentId == null) {
            tbMenu.setParentId(0);
        }
        //设置参数
        String s = JSON.toJSONString(tbMenu.getOptList());
        tbMenu.setOptType(s);
        if (tbMenuMapper.insert(tbMenu) > 0) {
            return ResponseResult.okResult("添加成功");
        }
        return ResponseResult.errorResult(500,"添加失败");
    }

    @Override
    public ResponseResult selectList(String menuName) {
        // 判断权限
        TbRole role = getRole();
        if (role.getRoleName().equals("超级管理员") || role.getRoleName().equals("管理员")) {
           // 执行查询
            List<TbMenu> tbMenus = tbMenuMapper.selectList(Wrappers.<TbMenu>lambdaQuery().like(StringUtils.checkValNotNull(menuName), TbMenu::getMenuName, menuName));
            tbMenus.forEach(tbMenu -> {
                TbMenu tbMenuName = tbMenuMapper.selectOne(Wrappers.<TbMenu>lambdaQuery().eq(TbMenu::getId, tbMenu.getParentId()));
                if (tbMenuName != null) {
                    String parentName = tbMenuName.getMenuName();
                    tbMenu.setParentName(parentName);
                }

            });
            return ResponseResult.okResult(tbMenus);
        }
        return ResponseResult.errorResult(500,"权限不足");
    }

    @Override
    public ResponseResult updateMenu(TbMenu tbMenu) {
        // 判断权限
        TbRole role = getRole();
        if (!role.getRoleName().equals("超级管理员")) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //判断参数
        if (tbMenu == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Integer parentId = tbMenu.getParentId();
        if (parentId == null) {
            tbMenu.setParentId(0);
        }
        if (tbMenuMapper.updateById(tbMenu) > 0) {
            return ResponseResult.okResult("修改成功");
        }
        return ResponseResult.errorResult(500,"添加失败");
    }
    @Resource
    private TbRoleMenuMapper tbRoleMenuMapper;
    @Override
    @Transactional
    public ResponseResult deleteMenu(Integer id) {
        //判断权限
        TbRole role = getRole();
        if (!role.getRoleName().equals("超级管理员")) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        int i = tbMenuMapper.deleteById(id);
        //删除完成权限之后要删除其对应的角色权限
        tbRoleMenuMapper.delete(Wrappers.<TbRoleMenu>lambdaQuery().eq(TbRoleMenu::getMenuId, id));
        if (i > 0) {
            return ResponseResult.okResult("删除成功");
        }
        return ResponseResult.errorResult(500,"删除失败");
    }

    @Override
    public ResponseResult getParent() {
        //查询父级菜单
        List<TbMenu> tbMenus = tbMenuMapper.selectList(Wrappers.<TbMenu>lambdaQuery().eq(TbMenu::getParentId, 0));
        return ResponseResult.okResult(tbMenus);
    }

    @Override
    public ResponseResult menuAllList() {
        List<TbMenu> tbMenuList = this.list(Wrappers.<TbMenu>lambdaQuery().eq(TbMenu::getParentId, 0));
        tbMenuList.forEach(tbMenu -> {
            List<TbMenu> tbMenus = this.list(Wrappers.<TbMenu>lambdaQuery().eq(TbMenu::getParentId, tbMenu.getId()));
            tbMenu.setChildren(tbMenus);
        });
        return ResponseResult.okResult(tbMenuList);
    }
}
